#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace log_ns;
const static u_int16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};
using func_t = std::function<std::string(std::string)>;

class UdpServer : public nocopy
{
public:
    UdpServer(func_t func, uint16_t localport = defaultport)
        : _func(func),
          _sockfd(defaultfd),
          _port(localport),
          _isrunning(false)
    {
    }

    void InitServer()
    {
        // 1.创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success,_sockfd:%d\n", _sockfd);

        // 2.bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // 服务器端，进行任意IP地址绑定

        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "socket bind success\n");
    }
    void Start()
    {
        _isrunning = true;
        char inbuff[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuff, sizeof(inbuff) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                InetAddr addr(peer);
                inbuff[n] = 0;
                std::cout << "[" << addr.Ip() << "]#" << inbuff << std::endl;
                std::string result = _func(inbuff);
                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr *)&peer, len);
            }
            else
            {
                std::cout << "recvform , error" << std::endl;
            }
        }
    }
    ~UdpServer()
    {
        if (_sockfd > defaultfd)
            ::close(_sockfd);
    }

private:
    uint16_t _port;
    int _sockfd;
    bool _isrunning;
    func_t _func;
};